<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\MealCardOrder;
use App\Models\MealCard;
use App\Models\MealUserCard;
use App\Models\CircleCardPrice;
use App\Models\Circle;
use App\Models\User;
use App\Models\Share;
use App\Services\OSS;
use Illuminate\Support\Facades\Redis;
use DB;

class MealCardController extends Controller
{
    /**
     * 创建饭卡
     */
    public function mealCardDesign() 
    {
        // self::cardSortCreate('Create');
        $circles = Circle::all();
    	return view('mealcard.design',['circles'=>$circles]);
    }

    /**
     * 执行创建操作
     */
    public function cardCreateAction(Request $request) 
    {
        $post = $request->only(['cardname','business_type','starttime','stoptime','frequency','mealprice','once','price','desc','limitday','range_id','delivery_free']);
        $card_type = ['SJ'=>0,'CK'=>1,'XS'=>2,'ZH'=>3];
        if(!isset($card_type[$post['business_type']])){
            return response()->json(['success'=>false,'code'=>'1','message'=>'请选择卡的类型！']);
        }
        if($post['business_type']=='XS'&&$post['limitday']<0){
            return response()->json(['success'=>false,'code'=>'0','message'=>'创建完成！']);
        }
        if($post['business_type']=='ZH'&&$post['num_198']<=0&&$post['num_258']<=0&&$post['num_298']<=0){
            return response()->json(['success'=>false,'code'=>'3','message'=>'请填写组合卡次数']);
        }
        $file = $request->file('mealcardBackground');
        $fileExt = ltrim($file->getClientOriginalExtension(),'.');
        $fileName = '/'.md5(uniqid(microtime(true),true)).'.'.$fileExt;
        $filePath = 'MealCardImgs';
        $upRes = OSS::publicUpload(config('aliyun.BucketName'),$filePath.$fileName,$file);
        if(!$upRes){
            return response()->json(['success'=>false,'code'=>'001','message'=>'图片上传失败！']);
        }
        $card = new MealCard;
        $nowtime = time();
        if(is_array($post['range_id'])){
            $post['range_id'] = implode(',', $post['range_id']);
        }
        $cardData = [
            'type'=>$card_type[$post['business_type']],
            'num'=>trim($post['frequency']),
            'start_time'=>trim($post['starttime']),
            'stop_time'=>trim($post['stoptime']),
            'day_once'=>trim($post['once']),
            'meal_max_price'=>trim($post['mealprice']),
            'card_price'=>trim($post['price']),
            'card_sales'=>0,
            'card_status'=>1,
            'card_img'=> $fileName,
            'card_name'=> $post['cardname'],
            'card_desc'=> preg_replace("/\\r\\n/",'&&&',$post['desc']),
            'card_frequency'=> $post['limitday'],
            'card_param'=> '',
            'insert_time'=>$nowtime,
            'update_time'=>0,
            'range_id'=>trim($post['range_id']),
            'delivery_free'=>trim($post['delivery_free'])
        ];
        $cardsortall = Redis::HGETALL('card_sort');
        if($post['business_type']=='ZH'){
            $cardData['num_198'] = $post['num_198'];
            $cardData['num_258'] = $post['num_258'];
            $cardData['num_298'] = $post['num_298'];
        }
        $res = $card->create($cardData);
        if($res){
            Redis::hset('card_sort',$res->card_id,count($cardsortall));
            return response()->json(['success'=>true,'code'=>'0','message'=>'创建完成！']);
        }else{
            return response()->json(['success'=>false,'code'=>'2','message'=>'创建出错，请联系开发人员处理！']);
        }
    }

    /**
     * 修改饭卡属性 
     */
    public function updateCard(Request $request)
    {
        $nowtime = time();
        $post = $request->only(['cardid','cardname','business_type','starttime','stoptime','frequency','mealprice','once','price','desc','limitday','activity_price','activity_price_select','cardstatus','circle_id','range_id','delivery_free']);
        // dd($post);
        $card_huodong_de = ['SE'=>0,'CE'=>1,0=>'SE',1=>'CE'];
        $card_status_de = ['XJ'=>0,'SJ'=>1,0=>'XJ',1=>'SJ'];
        $delivery_status_de = ['SF'=>0,'MF'=>1,0=>'SF',1=>'MF'];
        $card = MealCard::find($post['cardid']);
        if(!$card){
            return reponse()->json(['success'=>false,'code'=>'1','message'=>'对不起没有查询到该饭卡！']);
        }
        if(is_array($post['range_id'])){
            $post['range_id'] = implode(',', $post['range_id']);
        }
        $editData = [
            'num'=>trim($post['frequency']),
            'start_time'=>trim($post['starttime']),
            'stop_time'=>trim($post['stoptime']),
            'day_once'=>trim($post['once']),
            'meal_max_price'=>trim($post['mealprice']),
            'card_name'=>trim($post['cardname']),
            'card_desc'=>trim($post['desc']),
            'range_id'=>trim($post['range_id']),
            'delivery_free'=>$delivery_status_de[$post['delivery_free']],
        ];

        if($card_status_de[$card->card_status]!=$post['cardstatus']){
            
            if($post['cardstatus']=='XJ'){
                self::cardSort('del',$post['cardid']);
            }else if($post['cardstatus']=='SJ'){
                self::cardSort('add',$post['cardid']);
            }
            $editData['card_status'] = $card_status_de[$post['cardstatus']];
        }
        if($card_status_de[(int)$card->card_activity_price>0]!=$post['activity_price_select']||$post['activity_price']!=$card->card_activity_price){
            $editData['card_activity_price'] = $post['activity_price'];
        }
        if($post['business_type']==2){
            $editData['card_frequency'] = trim($post['limitday']);
        }else if($post['business_type']==3){
            $editData['num_198'] = trim($post['num_198']);
            $editData['num_258'] = trim($post['num_258']);
            $editData['num_298'] = trim($post['num_298']);
        }
        if($request->hasFile('mealcardBackground')){
            $backcard = $request->file('mealcardBackground');
            $fileExt = ltrim($backcard->getClientOriginalExtension(),'.');
            $filename = '/'.md5(uniqid(microtime(true),true)).'.'.$fileExt;
            $filePath = 'MealCardImgs';
            $upres = OSS::publicUpload(config('aliyun.BucketName'),$filePath.$filename,$backcard);
            if(!$upres){
                return response()->josn(['success'=>false,'code'=>'2','message'=>'图片上传失败，请稍后再试！']);
            }
            $editData['card_img'] = $filename;
        }
        $card = new MealCard;
        $editData['card_price'] = trim($post['price']);
        // if(empty($post['circle_id'])){
        //     $editData['card_price'] = trim($post['price']);
        // }else{
        //     $circleprice = new CircleCardPrice;
        //     $resss = $circleprice->add([
        //         'circle_id'=>$post['circle_id'],
        //         'card_id'=>$post['cardid'],
        //         'price'=>$post['price'],
        //     ]);
        //     if(!$resss['success']){
        //         return response()->json($resss);
        //     }
        // }
        $res = $card->editAttr($editData,$post['cardid']);
        if($res){
            return response()->json(['success'=>true,'code'=>0,'message'=>'饭卡修改信息已生效！']);
        }else{
            return response()->josn(['success'=>false,'code'=>'2','message'=>'系统出错，修改失败！']);
        }
    }

    // public function 

    /**
     * 管理饭卡
     */
    public function manageCard(Request $request)
    {
        $cards = MealCard::where('card_status','1')->where(function($q)use($request){
            if($request->input('circle_id',false)){
                return $q->whereRaw('(FIND_IN_SET('.$request->input('circle_id',false).',range_id))');
            }
        })->selectRaw('*,null as range_text')->get();
        // self::cardSortCreate('Create');
        $cardsort = Redis::HGETALL('card_sort');
        // dd($cardsort);
        if(!empty($cardsort)){
            foreach ($cards as $key => $value) {
                $cards[$cardsort[$value->card_id]] = $value;
            }
        }
        $downcards = MealCard::where('card_status','0')->get();
        $circles = Circle::all();
        return view('mealcard.manage',['cards'=>$cards,'sort'=>$cardsort,'downcards'=>$downcards,'circles'=>$circles]);
        // return view('mealcard.manage',['cards'=>$cards,'sort'=>$cardsort,'downcards'=>$downcards]);
    }

    /**
     * 饭卡出售订单
     */
    public function orderList(Request $request)
    {
        $order = new MealCardOrder;
        
        $pay_de = ['zhifu'=>1,'weizhifu'=>0,'default'=>-1,''=>-1,'weifu'=>-2];
        $orders = $order->leftJoin('lexiang_user','lexiang_user.user_id','=','lexiang_card_order.user_id')
        ->leftJoin('lexiang_meal_card','lexiang_meal_card.card_id','=','lexiang_card_order.card_id')
        ->selectRaw('lexiang_card_order.*,lexiang_user.nicename,lexiang_meal_card.card_name,lexiang_user.share_userid,null as share_user_name,lexiang_user.circle_range_id,null as sucircle_name,lexiang_user.tel')
        ->where(function($query)use($request,$pay_de){
            $pay = $request->input('pay','default');
            $starttime = $request->input('starttime',false);
            $endtime = $request->input('endtime',false);
            if($starttime&&$endtime){
                $query = $query->whereBetween('lexiang_card_order.insert_time',[$starttime,$endtime]);
            }
            if($pay_de[$pay]>=0){
                $query = $query->where('lexiang_card_order.order_status',$pay_de[$pay]);
            }
            if($request->input('circle_range_id',false)){
                $query = $query->where('lexiang_user.circle_range_id',$request->input('circle_range_id',false));
            }
            return $query;
        })
        ->orderBy('lexiang_card_order.insert_time','desc')
        ->paginate(15);
        $successorder = $order->where('order_status','1')->count();
        $orderstatus_de = ['-1'=>'已退款','0'=>'未支付','1'=>'已完成'];
        return view('mealcard.cardorder',['orders'=>$orders,'orderstatus_de'=>$orderstatus_de,'successorder'=>$successorder]);
    }

    /**
     * 饭卡信息获取
     */
    public function cardInfo(Request $request)
    {
        $card = MealCard::where('card_id',$request->input('card_id'))->first();
        if($card){
            return response()->json(['success'=>true,'code'=>'0','message'=>'信息获取成功','card'=>$card]);
        }else{
            return response()->json(['success'=>false,'code'=>'1','message'=>'饭卡信息无记录','card'=>[]]);
        }
    }

    /**
     * 删除饭卡
     */
    public function delCard(Request $request)
    {
        $cardid = $request->input('cardid');
        $result = MealCard::where('card_id',$cardid)->delete();
        if($result){
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'删除成功'
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'删除出错，请稍后再试'
            ]);
        }
    }

    /**
     * 饭卡排序
     */
    public function cardSortAction(Request $request)
    {
        if(!(bool)Redis::hgetall('card_sort')){ 
            self::cardSortCreate('Create');
        }
        $post = $request->only(['list','cards']);
        $list = explode(',',$post['list']);
        $cards_l = explode(',',$post['cards']);
        $sort = [];
        for ($i=0; $i < count($cards_l); $i++) {
            $sort[$cards_l[$i]] = $i;
        }
        Redis::del('card_sort');
        Redis::hmset('card_sort',$sort);
        return response()->json(['success'=>true,'code'=>'1','message'=>'排序已重置。','sort'=>$sort]);
    }

    /**
     * 饭卡信息排序
     */
    public static function cardSort($action=false,$cardid=false)
    {

        $cards = MealCard::where('card_status','1')->select('card_id')->get()->toArray();

        $sort = Redis::HGETALL('card_sort');

        $sortif = (bool)$sort;

        if($action=='del'){// 删除
            if($sortif){
                Redis::hDel('card_sort',$cardid);
                self::cardSortCreate('Refresh',$cards);
            }else{
                self::cardSortCreate('Create',$cards);
            }
            return true;
        }

        if($action=='add'){
            if($sortif){
                Redis::hSet('card_sort',$cardid,count($sort));
            }else{
                self::cardSortCreate('Create',$cards);
            }
            return true;
        }
    }

    /**
     * 创建 / 刷新饭卡排序
     */
    public static function cardSortCreate($a,$cards=false)
    {
        if($a=='Refresh'){
            $cards = Redis::HGETALL('card_sort');
            $sort = [];
            $i = 0;
            foreach ($cards as $key => $value) {
                $sort[$key] = $i;
                $i += 1;
            }

        }else if($a=='Create'){
            Redis::Del('card_sort');
            if(!$cards) $cards = MealCard::where('card_status','1')->select('card_id')->get()->toArray();
            $sort = [];
            $cardscount = count($cards);
            for ($i=0; $i < $cardscount; $i++) {
                $sort[$cards[$i]['card_id']] = $i;
            }
        }else{
            $sort = [];
        }
        return Redis::hmset('card_sort',$sort);
    }   

    /**
     * 添加次数
     */
    public function addOne(Request $request)
    {
        $card = MealUserCard::find($request->card_id);

        $card->card_num = $request->input('card_number',0);

        if($card->save()){
            return response()->json(['success'=>true,'code'=>'000','message'=>'修改成功']);
        }else{
            return response()->json(['success'=>false,'code'=>'003','message'=>'修改出错，请稍后再试']);
        }
    }

    /**
     * 饭卡列表
     */
    public function cardBuys(Request $request)
    {
        $card = new MealCard;
        $usercard = new MealUserCard;
        $userid = $request->input('user_id');
        $type = $request->input('type',1);
        $userinfo = User::where('user_id',$userid)->first();
        $w = false;
        if(!empty($userinfo->circle_range_id)){
            $w = (string) $userinfo->circle_range_id;
        }
        $cardInfo = $card->when($w,function($q)use($w){
            /*return $q->where([
                ['card_status','=',1],
                ['range_id','=',0],
            ])->orWhere([
                ['card_status','=',1],
                ['range_id','=',$w],
            ]);*/
            return $q->whereRaw('(`card_status` = 1 and `range_id` = 0) or (`card_status` = 1 and FIND_IN_SET('.$w.',range_id))');
        })->when(!$w,function($q)use($w){
            return $q->where([
                ['card_status','=',1],
                ['range_id','=','0'],
            ]);
        })->get();

        $cardSort = Redis::HGETALL('card_sort');
        $mycard = $usercard
        ->leftJoin('lexiang_meal_card','lexiang_meal_card.card_id','=','lexiang_meal_user_card.cards_id')
        ->where([
            ['lexiang_meal_user_card.users_id','=',$userid],
        ])
        ->where(function($q)use($type){
            if($type==1){
                $q = $q->where('lexiang_meal_user_card.card_invalid',1);
                $q = $q->where('lexiang_meal_user_card.card_num','>',0);
                return $q;
            }else if($type == 0){
                return $q->where('lexiang_meal_user_card.card_invalid',0);
            }
        })
        ->select('lexiang_meal_user_card.*','lexiang_meal_card.card_img','lexiang_meal_card.start_time','lexiang_meal_card.stop_time','lexiang_meal_card.card_name','lexiang_meal_card.card_desc')
        ->get();
        if(!empty($cardSort)){
            $newdata = [];
            for ($i=count($cardInfo) - 1; $i >= 0; $i--) {
                if($cardInfo[$i]->card_id == 198 && $userinfo->circle_range_id == 20){
                    continue;
                }
                $newdata[$cardSort[$cardInfo[$i]->card_id]] = $cardInfo[$i];
            }

            $cardInfo = $newdata;
        }
        if($userinfo->circle_range_id == 3 || $userinfo->circle_range_id == 5 || $userinfo->circle_range_id == 9 || $userinfo->circle_range_id == 11){
            $cardInfo = [];
        }
        return response()->json([
            'success'=>true,
            'code'=>'000',
            'message'=>'查询完成',
            'data'=>$cardInfo,
            'dataUser'=>$mycard
        ]);
    } 

    public function giftCard(Request $request)
    {
        $cards = MealCard::where('card_status','1')->get();
        
        return view('mealcard.gift',['cards'=>$cards]);
    }

    /**
     * 赠予饭卡
     */
    public function giftCardAction(Request $request)
    {
        $tel = $request->input('tel');
        $cardid = $request->input('card_id');
        $buytype = $request->input('buy_type',3);
        $card = new MealCard;
        $cardOrder = new MealCardOrder;
        $usercard = new MealUserCard;
        $userinfo = User::where([
            ['tel','=',$tel],
            ['user_ttp','=',1],
        ])->first();
        if(!$userinfo){
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'没有此用户，请核实手机号',
            ]);
        }
        $cardInfo = $card->where('card_id',$cardid)->first();
        if(empty($cardInfo->card_activity_price)){
            $pricecard = $cardInfo->card_price;
        }else{
            $pricecard = $cardInfo->card_activity_price;
        }
        $data = [
            'user_id'=>$userinfo->user_id,
            'order_price'=>($pricecard * 100),
            'card_id'=>$cardInfo->card_id,
            'order_status'=>1,
            'insert_time'=>date('Y-m-d H:i:s'),
            'order_desc'=>'赠送饭卡--'.$cardInfo->card_name,
            'user_card_id'=>$cardid,
            'buy_type'=>$buytype
        ];
        $createOrderData = $cardOrder->add($data);
        if(!$createOrderData['success']){
            return response()->json($createOrderData);
        }
        $cardOrderInfo = $cardOrder->where('order_num',$createOrderData['data']['order_num'])->first();
        $createData = [
            'cards_id'=>$cardInfo->card_id,
            'users_id'=>$userinfo->user_id,
            'card_type'=>$cardInfo->type,
            'card_num'=>$cardInfo->num,
            'card_max_price'=>$cardInfo->meal_max_price,
            'order_id'=>$cardOrderInfo->order_id,
            'card_endtime'=>'',
        ];
        $res = $usercard->createCard($createData);
        return response()->json($res);
    }

    /**
     * 购买饭卡下单
     */
    public function order(Request $request)
    {
        $userid = $request->input('users_id',false);
        $cardid = $request->input('cards_id',false);
        if(!$userid || !$cardid){
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'当前环境无法进行支付',
            ]);
        }
        require(base_path('app/Packages/weixinpay/').'WeixinPay.php');
        $card = new MealCard;
        $cardOrder = new MealCardOrder;
        $cardInfo = $card->where('card_id',$request->input('cards_id'))->first();
        if(empty($cardInfo->card_activity_price)){
            $pricecard = $cardInfo->card_price;
        }else{
            $pricecard = $cardInfo->card_activity_price;
        }
        if($cardInfo->card_id == 13){
            $alercard = $cardOrder->where([
                ['user_id','=',$request->input('users_id')],
                ['order_status','=',1],
            ])->first();
            if($alercard){
                return response()->json([
                    'success'=>false,
                    'code'=>'003',
                    'message'=>'体验卡仅限新用户购买，您可选择享受其他优惠套餐！',
                ]);
            }
        }
        if($cardInfo->card_id == 24){
            $alercard = $cardOrder->where([
                ['user_id','=',$request->input('users_id')],
                ['order_status','=',1],
                ['order_price','>',9900],
            ])->first();
            if(!$alercard){
                return response()->json([
                    'success'=>false,
                    'code'=>'003',
                    'message'=>'本活动只回馈老用户，新用户需购买过一次月卡后方可购买',
                ]);
            }
        }
        $data = [
            'user_id'=>$request->input('users_id'),
            'order_price'=>($pricecard * 100),
            'card_id'=>$cardInfo->card_id,
            'order_status'=>0,
            'insert_time'=>date('Y-m-d H:i:s'),
            'order_desc'=>'购买饭卡--'.$cardInfo->card_name
        ];
        $res = $cardOrder->add($data);
        if(!$res['success']){
            return response()->json($res);
        }
        $wx = new \Wxpayandroid;
        $backurl = "http://console.jiashilexiang.cn/api/card/notifyurl/";
        return response()->json($wx->WeixinpayXcx($pricecard,$res['data']['order_num'],"嘉时乐享 - 套餐卡",$request->input('openid'),$backurl));
    }

    /**
     * 买饭卡回调
     */
    public function notifyUrl(Request $request)
    {
        $nowtime = time();
        $xml = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
        // file_put_contents(base_path('storage/logs/').'wxpay.log', $xml."\n---------\n", FILE_APPEND);
        // 将服务器返回的XML数据转化为数组
        // 将XML转为array
        // 禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        file_put_contents(base_path('storage/logs/').'wxpay.log', json_encode($data)."\n---------\n", FILE_APPEND);
        $card = new MealCard;
        $cardOrder = new MealCardOrder;
        $usercard = new MealUserCard;
        $cardInfo = $cardOrder->where('order_num',$data['out_trade_no'])->first();
        if($cardInfo->order_status == 1){
            echo 'success';die;
        }
        $buycardInfo = $card->where('card_id',$cardInfo->card_id)->first();
        if($data['result_code']!='SUCCESS'){
            echo 'fail';die;
        }
        $createData = [
            'cards_id'=>$buycardInfo->card_id,
            'users_id'=>$cardInfo->user_id,
            'card_type'=>$buycardInfo->type,
            'card_num'=>$buycardInfo->num,
            'card_max_price'=>$buycardInfo->meal_max_price,
            'order_id'=>$cardInfo->order_id,
            'card_endtime'=>'',
        ];
        $res = $usercard->createCard($createData);
        if(!$res['success']){
            echo 'fail';die;
        }
        $cardInfo->order_status = 1;
        $cardInfo->user_card_id = $res['data']['buy_card_id'];
        $cardInfo->wx_order_number = $data['transaction_id'];
        $buycardInfo->card_sales = $buycardInfo->card_sales+1;
        if($cardInfo->save()){
            $sendres = $this->buyCardEnd($cardInfo->user_id,$buycardInfo->card_id,$cardInfo->order_id);
            file_put_contents(base_path('storage/logs/').'wxpay.log', json_encode($sendres)."\n----gggg-----\n", FILE_APPEND);
            echo 'success';die;
        }else{
            echo 'fail';die;
        }
    }

    /**
     * 全款退款
     */
    public function tuikuan(Request $request)
    {
        DB::beginTransaction();

        $order = new MealCardOrder;
        $userCard = new MealUserCard;
        $orderinfo = $order->where('order_id',$request->input('order_id'))->first();
        $cardInfo = $userCard->where('order_id',$orderinfo->order_id)->first();
        $cardInfo->card_invalid = 0;
        $cardInfo->card_num = 0;
        $orderinfo->order_status = -1;

        if(!$cardInfo->save()){
            DB::rollBack();
            return response()->json([
                'success'=>false,
                'code'=>'004',
                'message'=>'退款数据查询错误',
                'data'=>$cardInfo
            ]);
        }

        if(!$orderinfo->save()){
            DB::rollBack();
            return response()->json([
                'success'=>false,
                'code'=>'004',
                'message'=>'退款数据查询错误',
                'data'=>$orderinfo
            ]);
        }

        // 执行退款
        require(base_path('app/Packages/weixinpay/').'WeixinPay.php');
        $wx = new \Wxpayandroid;
        $tui = $wx->refund(($orderinfo->order_price/100),$orderinfo->order_num);
        if($tui['success']){
            DB::commit();
        }
        return response()->json($tui);
    }

    /**
     * 购买完成
     */
    public function buyCardEnd($userid,$cardid,$orderid)
    {
        $cardorder = new MealCardOrder;
        $share = new Share;
        $user = new User;
        DB::beginTransaction();
        // $userid = $request->input('user_id');
        // $cardid = $request->input('card_id');
        // $orderid = $request->input('order_id');
        $cardInfo = $cardorder->where('order_id',$orderid)->first();
        // $cardInfo = $cardorder->where([['user_id','=',$userid],['card_id','=',$cardid],['order_status','=',1]])->whereBetween('insert_time',[date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59')])->first();
        if(!$cardInfo){
            return [
                'success'=>false,
                'code'=>'004',
                'message'=>'支付失败'
            ];
        }
        if($cardInfo->order_status != 1){
            return [
                'success'=>false,
                'code'=>'004',
                'message'=>'支付失败'
            ];
        }
        if(MealCard::where('card_id',$cardid)->value('card_price') < 99){
            return [
                'success'=>false,
                'code'=>'004',
                'message'=>'大于168可领取'
            ];
        }
        $userinfo = $user->where('user_id',$userid)->first();
        if(empty($userinfo->share_userid)){
            DB::rollback();
            return [
                'success'=>false,
                'code'=>'004',
                'message'=>'没有分享用户'
            ];
        }
        // $reuserinfo = $user->where('user_id',$userinfo->share_userid)->first();

        /*$res = $share->add([
            'share_to_userid'=>$userinfo->share_userid,
            'user_id'=>$userid,
            'card_id'=>$cardid,
            'buy_card_id'=>$cardInfo->user_card_id,
            'toorme'=>1
        ]);
        if(!$res['success']){
            DB::rollback();
            return $res;
        }*/
        $share = new Share;
        $res = $share->add([
            'share_to_userid'=>$userinfo->user_id,
            'user_id'=>$userinfo->share_userid,
            'card_id'=>$cardid,
            'buy_card_id'=>$cardInfo->user_card_id,
            'toorme'=>0
        ]);
        if(!$res['success']){
            DB::rollback();
            return $res;
        }
        $userinfo->share_userid = 0;
        if($userinfo->save()){
            DB::commit();
            return [
                'success'=>true,
                'code'=>'000',
                'message'=>'发送成功'
            ];
        }else{
            DB::rollback();
            return [
                'success'=>false,
                'code'=>'000',
                'message'=>'发送失败'
            ];
        }
    }

    /**
     * 分享用户来源保存
     */
    public function saveSource(Request $request)
    {   
        // $share = new Share;
        //     $share->add([
        //         'share_to_userid'=>$request->input('share_userid'),
        //         'user_id'=>$request->input('user_id'),
        //         'card_id'=>0
        //     ]);
        $user = User::where('user_id',$request->input('user_id'))->first();
        if(!$user){
            return response()->json([
                    'success'=>false,
                    'code'=>'004',
                    'message'=>"没有用户",
                    'data'=>$request->all()
                ]);
        }
        
        if($request->input('share_userid',false)){
            if($request->input('share_userid',false) == $request->input('user_id')){
                return response()->json([
                    'success'=>false,
                    'code'=>'004',
                    'message'=>"自己分享，无法继续"
                ]);
            }
            if(!empty($user->share_userid)){
                return response()->json([
                    'success'=>false,
                    'code'=>'004',
                    'message'=>"已经存在被分享朋友"
                ]);
            }
            
            $user->share_userid = $request->input('share_userid',0);
        }
        if($request->input('unionid',false)){
            $user->unionid = $request->input('unionid');
        }
        if($user->save()){
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'保存成功'
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'code'=>'006',
                'message'=>'保存出错，请稍后再试！'
            ]);
        }

    }

    
}
